package org.jash.utils

import android.annotation.SuppressLint
import androidx.arch.core.internal.SafeIterableMap
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import java.util.concurrent.atomic.AtomicBoolean

class SingleLiveData<T>:MutableLiveData<T>() {
    @SuppressLint("RestrictedApi")
    @Suppress("UNCHECKED_CAST")
    override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
        super.observe(owner, observer)
        val map =
            LiveData::class.java.getDeclaredField("mObservers").apply { isAccessible = true }
                .get(this) as SafeIterableMap<Observer<in T>, *>
        val version =
            LiveData::class.java.getDeclaredField("mVersion").apply { isAccessible = true }
                .get(this)
        val entry = map.newest()?.value
        Class.forName("androidx.lifecycle.LiveData\$ObserverWrapper").getDeclaredField("mLastVersion").apply {
            isAccessible = true
            set(entry, version)
        }
    }
}